# -*- coding: utf-8 -*-
import urllib
import urllib2
import cookielib
import os
from bs4 import BeautifulSoup
import sys;
reload(sys);
sys.setdefaultencoding("utf8")
#声明一个CookieJar对象实例来保存cookie
cookie = cookielib.CookieJar()
#利用urllib2库的HTTPCookieProcessor对象来创建cookie处理器
handler=urllib2.HTTPCookieProcessor(cookie)
#通过handler来构建opener
opener = urllib2.build_opener(handler)
# 登录教务系统的URL
loginUrl = 'http://gsmis.nuaa.edu.cn/nuaapyxx/login.aspx'
# 请求头文件
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36 SE 2.X MetaSr 1.0',
}
req = urllib2.Request(url=loginUrl,  headers=headers)
# 为了获得隐藏域__VIEWSTATE，先打开一次页面获得viewstate，再进行登录
opener.open(req)
result = opener.open(req)
content = result.read().decode('utf-8')
soup = BeautifulSoup(content, "lxml")
for tabb in soup.find_all(name='input', attrs={'name':'__VIEWSTATE'}):
    viewstate = tabb.attrs['value']
    print viewstate
postdata = urllib.urlencode({
    '__VIEWSTATE': viewstate,
    # 此处为用户名/学号
    '_ctl0:txtusername': '*********',
    '_ctl0:ImageButton1.x': '30',
    '_ctl0:ImageButton1.y': '26',
    # 此处为用户密码
    '_ctl0:txtpassword': '************'
})
req = urllib2.Request(url=loginUrl, data=postdata, headers=headers)
opener.open(req)
gradeUrl = 'http://gsmis.nuaa.edu.cn:81/nuaapyxx/grgl/xskccjcx.aspx'
req = urllib2.Request(url=gradeUrl, headers=headers)
result = opener.open(req)
content = result.read().decode('utf-8')
soup = BeautifulSoup(content, "lxml")
count = 0
num = 0
filename = u"成绩查询结果"
path = filename + ".txt"
[s.extract() for s in soup(name='tr', attrs={'bgcolor': '#C8E1FB'})]
for tabb in soup.find_all(name='tr', attrs={'nowrap':'nowrap'}):
    for tdd in tabb.find_all(name='font', attrs={'size':'2'}):
        count += 1
        if (count % 5 == 1):
            num += 1
            with open(path, "a") as fp:
                fp.write("%d.【课程】:“%s”, " %(num,tdd.get_text()))
        if (count % 5 == 4):
            with open(path, "a") as fp:
                fp.write("【成绩】:%s;\n" % tdd.get_text())
